import React, {useEffect, useState} from 'react'
import {
    Table, Pagination, Spin, Alert, Modal,
    Form,
    Input,
    Button,
    Row,
    Col,
    Space,
    message,
    Typography
} from 'antd';
import {
    UploadOutlined,
    FileExcelOutlined,
    WarningOutlined,
    StepForwardOutlined
} from '@ant-design/icons';
import backgroundImage from '../images/form_bg@2x.2d429e6ecd7d2c432e6f.png';
import {request} from "../utils/requset";
import {useSelector} from "react-redux";
import {useNavigate} from "react-router-dom";


const backgroundStyle = {
    backgroundImage: `url(${backgroundImage})`,
    backgroundSize: 'cover', // 使背景图片覆盖整个容器
    backgroundPosition: 'center', // 背景图片居中
    backgroundRepeat: 'no-repeat', // 防止背景图片重复
    // minHeight: '100vh', // 确保背景图片覆盖整个视口高度
    // 其他您需要的样式
};


const {Title} = Typography;

const NwProjectPage = () => {
    const [form] = Form.useForm();
    const [loading, setLoading] = useState(false);
    const [clearLoading, setClearLoading] = useState(false);
    const [runLoading, setRunLoading] = useState(false);
    const [error, setError] = useState(false);
    const [pageNum, setPageNum] = useState(1);
    const [pageSize, setPageSize] = useState(10);
    const [total, setTotal] = useState(0);
    const [dataSource, setDataSource] = useState([]);
    const [selectedRowKeys, setSelectedRowKeys] = useState([]); // 选中行的状态
    const [tableHeight, setTableHeight] = useState(500); // 默认高度
    const [searchParams, setSearchParams] = useState({key: '', value: ''}); // 搜索相关状态
    const [visible, setVisible] = useState(false);
    const [modalContent, setModalContent] = useState('');
    const [fileLoading, setFileLoading] = useState(false);
    const [filepath, setfilepath] = useState('');
    const [folderpath, setfolderpath] = useState('');


    const sysConfig = useSelector(state => state.pz.sysConfig);
    const navigator = useNavigate();

    // 在组件挂载时获取数据
    useEffect(() => {
        fetchData(pageNum, pageSize, searchParams);
    }, [sysConfig, pageNum, pageSize, searchParams]);


    // 动态设置表格高度
    useEffect(() => {
        const updateTableHeight = () => {
            const viewportHeight = window.innerHeight;
            const desiredHeight = viewportHeight / 2 - 100; // 例如，减去200像素用于其他内容
            setTableHeight(desiredHeight > 300 ? desiredHeight : 300); // 设置最小高度为300
        };

        updateTableHeight();
        window.addEventListener('resize', updateTableHeight);
        return () => window.removeEventListener('resize', updateTableHeight);
    }, []);


    const handleUpload = async () => {
        try {
            const values = await form.validateFields();
            const payload = {
                dwbh: sysConfig.dwbh,
                model: sysConfig.model,
                filepath: values.filepath
            };
            setLoading(true);
            await request.post('/nw_project/api/load_file', payload);
            message.success('文件上传成功！');
            await fetchData(pageNum, pageSize)
        } catch (error) {
            if (error.response) {
                // console.log(error)
                message.error(`文件上传失败: ${error.response.data.message?error.response.data.message:error.response.data.error}`);
            } else {
                // console.error(':', error);
                message.error('文件上传失败');
            }
        } finally {
            setLoading(false);
        }
    };


    const handleClearData = async () => {
        try {
            setClearLoading(true);
            // const values = await form.getFieldValue();
            const response = await request.post('/nw_project/api/clear', {
                dwbh: sysConfig.dwbh,
                model: sysConfig.model
            });
            const data = response.data;
            // console.log(data)
            // console.log(data ? data.code : 500)
            if (data && data.code === 200) {
                message.success('操作完成！');
            } else if (data && data.message) {
                message.error(data.message);
            }


            await fetchData(pageNum, pageSize)

        } catch (error) {
            if (error.response) {
                message.error(`操作失败: ${error.response.data.message?error.response.data.message:error.response.data.error}`);
            } else {
                // console.error('操作失败:', error);
                message.error('操作失败，请稍后再试。');
            }
        } finally {
            setClearLoading(false);
        }
    };


    const handleFolderSelect = async () => {
        setFileLoading(true);
        try {
            const response = await request.post('/select-file', {
                type: 'folder',
                filetype: '',
                path: folderpath,
            });
            const data = response.data;
            setfolderpath(data.path);
            form.setFieldsValue({folderpath: data.path});
        } catch (error) {
            // console.error('选择文件夹失败:', error);
            message.error('选择文件夹失败，请稍后再试。');
        } finally {
            setFileLoading(false);
        }
    };
    const handleFileSelect = async () => {
        setFileLoading(true);
        try {
            const response = await request.post('/select-file', {
                type: 'file',
                filetype: ['xlsx', 'xls', 'xlsm'],
                path: filepath,
            });
            const data = response.data;
            setfilepath(data.path);
            form.setFieldsValue({filepath: data.path});
        } catch (error) {
            // console.error('选择文件失败:', error);
            message.error('选择文件失败，请稍后再试。');
        } finally {
            setFileLoading(false);
        }
    };


    const NwProjectColumns = [
        {
            title: '模型',
            dataIndex: 'model',
            key: 'model',
            width: 150,
        },
        {
            title: '类型',
            dataIndex: 'qzq_type',
            key: 'qzq_type',
            width: 80,
        },
        {
            title: '型号编号',
            dataIndex: 'code',
            key: 'code',
            width: 100,
        },
        {
            title: '型号名称',
            dataIndex: 'name',
            key: 'name',
            width: 100,
        },
        {
            title: '会计年度',
            dataIndex: 'kjnd',
            key: 'kjnd',
            width: 100,
        },
        {
            title: '主业项目编号',
            dataIndex: 'hsm_xmbh',
            key: 'hsm_xmbh',
            width: 300,
            render: (text) => (
                <span>
                    {text && text.length > 280 ? (
                        <>
                            {text.slice(0, 20)}...
                            <a onClick={() => handleShowModal(text)}>查看</a>
                        </>
                    ) : (
                        text
                    )}
                </span>
            ),
        },
        {
            title: '计算方式',
            dataIndex: 'calc',
            key: 'calc',
            width: 100,
        },
        {
            title: '备注',
            dataIndex: 'remarks',
            key: 'remarks',
            width: 200,
        },
    ];

    const handleShowModal = (text) => {
        setModalContent(text);
        setVisible(true);
    };
    // 获取表格数据的函数
    const fetchData = async (currentPage = 1, size = 10, search = {key: '', value: ''}) => {
        setRunLoading(true);
        setError(null);
        try {
            // console.log(values)
            // console.log(currentPage)
            // 替换为你的实际 API URL
            const response = await request.post('/nw_project/api/pagedata', {
                    "dwbh": sysConfig.dwbh,
                    "model": sysConfig.model,
                    // "kjnd": "2024",
                    "pageNum": currentPage,
                    "pageSize": size
                }
            );

            const jsonData = response.data;
            // console.log(jsonData)
            // 设置分页相关的状态
            // setPageCount(jsonData.pageCount);
            setPageNum(jsonData.pageNum);
            setPageSize(jsonData.pageSize);
            setTotal(jsonData.total);
            // setTotalPage(jsonData.totalPage);

            // 设置表格数据源
            setDataSource(jsonData.data);
        } catch (err) {
            // console.error('数据获取失败:', err);
            setError('数据获取失败，请稍后再试。');
        } finally {
            setRunLoading(false);
        }
    };

    const handleGetData = () => {
        fetchData(pageNum, pageSize)
    }


    // 计算当前页显示的条数
    const startRow = (pageNum - 1) * pageSize + 1;
    const endRow = Math.min(pageNum * pageSize, total);
    // 页码变化时
    const onPageChange = (page, size) => {
        // console.log(page, size)
        setPageNum(page); // 设置当前页
        setPageSize(size); // 设置每页条数
    };

    const handleCancel = () => {
        setVisible(false);
    };

    return (
        <Row justify="center">

            <Col xs={24} sm={20} md={20}>
                <div className="config-page-layout float-center" style={backgroundStyle}>
                    <div className="upper-section">
                        <Title>
                            报表行配置
                            {/* 保存和运行按钮 */}
                            <Space className='float-right' style={{marginBottom: 16, marginLeft: 8}}>
                                <Button type="default" onClick={handleUpload} loading={loading} className='float-right'>
                                    <FileExcelOutlined/> 上传文件
                                </Button>
                                <Button type="primary" onClick={handleGetData} loading={runLoading}
                                        className='float-right'>
                                    刷新数据
                                </Button>
                                <Button type="primary" onClick={handleClearData} loading={clearLoading}
                                        className='float-right' danger>
                                    <WarningOutlined/>清空数据
                                </Button>
                                <Button type="default" onClick={()=>{navigator('/robot/rpa/operate')}} loading={runLoading} className='float-right'>
                                    报表生成<StepForwardOutlined />
                                </Button>
                            </Space>
                        </Title>

                        <Form
                            form={form}
                            layout="vertical"
                        >

                            <Row gutter={16}>
                                {/* 文件选择 */}
                                <Col xs={24} sm={12} md={8}>
                                    <Form.Item
                                        label="文件选择"
                                        name="filepath"
                                        rules={[{required: true, message: '请选择文件!'}]}
                                    >
                                        <Input
                                            placeholder="上传文件路径选择"
                                            className="file-select"
                                            readOnly
                                            suffix={
                                                <Button type="link" icon={<UploadOutlined/>} onClick={handleFileSelect}
                                                        disabled={fileLoading}>
                                                    选择
                                                </Button>
                                            }
                                        />
                                    </Form.Item>
                                </Col>
                            </Row>

                        </Form>
                    </div>

                    {/* 下部分的表格 */}
                    <div className="lower-section">
                        <div className="my-data-table-container">
                             <Title level={4}>报表行配置明细</Title>
                            {error && <Alert message={error} type="error" showIcon style={{marginBottom: 16}}/>}

                            <Spin spinning={loading}>
                                <Table
                                    columns={NwProjectColumns}
                                    dataSource={dataSource}
                                    rowKey="hsm_uuid"
                                    pagination={false} // 使用自定义的分页组件
                                    scroll={{x: 'max-content', y: tableHeight}} // 启用水平和垂直滚动
                                    rowClassName={(record) =>
                                        selectedRowKeys.includes(record.code) ? 'selected-row' : ''
                                    }
                                />
                                <Modal
                                    title="数据描述"
                                    open={visible}
                                    onCancel={handleCancel}
                                    footer={null}
                                >
                                    <p>{modalContent}</p>
                                </Modal>
                            </Spin>
                            <div>
                                <span>
                                    当前 {startRow}-{endRow} 条，共 {total} 条
                                </span>
                                <Pagination
                                    current={pageNum}
                                    pageSize={pageSize}
                                    total={total}
                                    showSizeChanger
                                    pageSizeOptions={['10', '20', '50', '100']} // 限制每页条目数选项
                                    style={{marginTop: 16, textAlign: 'right'}}
                                    onChange={onPageChange}      // 页码变化时触发
                                />
                            </div>
                        </div>
                    </div>
                </div>
            </Col>
        </Row>
    )
}

export default NwProjectPage